package com.lft.freshordering.controller;


import com.lft.freshordering.entity.Audit;
import com.lft.freshordering.response.R;
import com.lft.freshordering.response.StatusEnum;
import com.lft.freshordering.service.impl.AuditServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.lft.freshordering.entity.Audit;
import com.lft.freshordering.entity.User;
import com.lft.freshordering.response.R;
import com.lft.freshordering.service.IAuditService;
import com.lft.freshordering.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import static com.mysql.cj.conf.PropertyKey.logger;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyhxzy
 * @since 2024-12-02
 */
@RestController
@RequestMapping("/audit")
public class AuditController {

    @Autowired
    private AuditServiceImpl auditService;

    /**
     * 查询所有审核信息`1审核
     */
    @GetMapping("/selall")
    public R<List<Audit>> selAll() {
        return R.success(auditService.selAll());
    }

    @PostMapping("/update")
    public R<String> updateAuditlqw(@RequestBody Audit audit) {
        // 调用auditService的updateById方法尝试更新审核信息
        // 根据更新结果返回相应的响应对象
        return auditService.updateById(audit) ? R.success("更新成功") : R.error(500, "更新失败");
    }

    @GetMapping("/getAudit")
    public R<Audit> getAudit(@RequestParam Integer userId) {
        Audit audit = auditService.getById(userId);
        return R.success(audit);
    }
    @GetMapping("/updateaudit/{aid}")
    public R updateAuditStatus(@PathVariable Integer aid) {
        Integer updateaudit = auditService.updateaudit(aid);
        System.out.println("---审核状态已更新---");
        return R.success(updateaudit);
    }
    @GetMapping("selectByuserId/{userId}")
    public R selectByUserId(@PathVariable Integer userId) {
        Audit audit = auditService.selectByUserId(userId);
        return R.success(audit);
    }

//    @PutMapping("/status")
//    public void updateAuditStatus(@RequestParam Integer reviewStatus, @RequestParam Integer auditId) {
//        System.out.println("reviewStatus: " + reviewStatus);
//        System.out.println("auditId: " + auditId);
//        auditService.updateAuditStatus(reviewStatus, auditId);
//
//    }

    @GetMapping("/AuditIdByName/{shopName}")
    public R getAuditIdByName(@PathVariable String shopName) {
        return R.success(auditService.selectAuditIdByName(shopName));
    }

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/selectbyid/{id}")
    private R selectByid(@PathVariable Integer id) {
        System.out.println("id: " + id);
        if (!isValidId(id)) {
            return R.error(400, "参数错误");
        }

        return getAuditById(id);
    }


    private boolean isValidId(Integer id) {
        return id != null && id > 0;
    }


    private R getAuditById(Integer id) {
        String cacheKey = "audit:" + id;

        Audit audit = (Audit) redisTemplate.opsForValue().get(cacheKey);
        if (audit == null) {
            audit = fetchAuditFromDatabase(id);
            if (audit != null) {
                redisTemplate.opsForValue().set(cacheKey, audit);
            }
        }
        return R.success(audit);
    }


    private Audit fetchAuditFromDatabase(Integer id) {
        try {
            return auditService.selectAudit(id);
        } catch (DataAccessException e) {
            R.error(400, "数据库访问异常");
            return null;
        } catch (IllegalArgumentException e) {
            R.error(400, "非法参数异常");
            return null;
        } catch (Exception e) {
            R.error(400, "未知异常");
            return null;
        }
    }

    @PutMapping("/updateAudit")
    public R updateAudit(@RequestBody Audit audit) {
        System.out.println("audit: " + audit);
        if (audit.getUserName() == null || audit.getPhone() == null) {
            return R.error(400, "参数错误");
        }
        try {
            int i = auditService.updateAudit(audit);
            if (i > 0) {
                Boolean delete = redisTemplate.delete("audit:" + audit.getUserId());
                if (delete != null && delete) {
                    return R.success("更新成功");
                } else {

                    return R.error(500, "更新成功，但缓存删除失败");
                }
            }
        } catch (Exception e) {
            return R.error(500, "更新失败: " + e.getMessage());
        }
        return R.error(400, "更新失败");
    }

    @Autowired
    private IAuditService iAuditService;

    @RequestMapping("/audit")
    public R audit(@RequestBody Audit audit) {

        System.out.println(audit);
        int i = iAuditService.addAudit(audit);
        return R.success(i);
    }
    @RequestMapping("/reject")
    public R rejectAudit(@RequestBody Audit mm) {
        System.out.println("---------");
        System.out.println(mm);
        Integer id = mm.getAuditId();
        Integer reviewStatus= mm.getReviewStatus();
        String cause = mm.getCause();
        int result = auditService.updateAuditStatusToReject(id, reviewStatus, cause);
        if(result > 0){
            return R.success("审核已驳回");
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }



    @RequestMapping("/getAuditList")
    public R getAuditList() {
        List<Map> auditList = auditService.getAuditList();
        return R.success(auditList);
    }

    @RequestMapping("/updateAuditStatus/{id}")
    public R updateAuditStatus11(@PathVariable Integer id) {
        int i = auditService.updateAuditStatus(id);
        return R.success(i);
    }

    @RequestMapping("/updateAuditStatusToReject/{id}")
    public R updateAuditStatusToReject(@PathVariable Integer id) {
        int i = auditService.updateAuditStatusToReject(id);
        return R.success(i);
    }

    @RequestMapping("/selectauditdd/{id}")
    public R selectauditdd(@PathVariable Integer id) {
        Map map = auditService.selectauditdd2(id);
        return R.success(map);
    }
}

